package com.za.plugin.transfer.func;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;

/**
 * Json 函数支持
 */
public class JsonArrayAggFunctionTransfer implements FunctionTransfer{
    @Override
    public boolean isSupport(String sql) {
        return sql.toLowerCase().contains("json_arrayagg");
    }

    @Override
    public String transfer(String sql) {
        MySqlStatementParser parser = new MySqlStatementParser(sql);
        SQLStatement sqlStatement = parser.parseStatement();
        sqlStatement.accept(new MySqlASTVisitorAdapter() {
            @Override
            public boolean visit(SQLMethodInvokeExpr expr) {
                if (expr.getMethodName().equalsIgnoreCase("json_arrayagg")) {
                    expr.setMethodName("json_array");
                }
                return super.visit(expr);
            }
        });
        return SQLUtils.toMySqlString(sqlStatement);
    }
}

//        return sql.toLowerCase().replace("json_arrayagg","json_array");
